package mi.payment.ui.print;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.View;
import android.widget.LinearLayout;

import lainey.ui.dialog.IconHintDialog;
import lainey.ui.widget.TitleView;
import mi.payment.R;
import mi.payment.constants.Params;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.SalesSlipPrintSettings;
import mi.payment.settings.SalesSlipPrintSettingsOperation;
import mi.payment.ui.base.ParentActivity;
import mi.payment.ui.print.helper.PrintController;
import mi.payment.utils.print.DataPrinterKernel;
import sunmi.payment.L3.L3BroadcastHelper;
import woyou.aidlservice.jiuiv5.ICallback;

/**
 * 补打上笔凭证
 */
public class FillInTheCertificateActivity extends ParentActivity {

    private static final String EXTRA_IS_L3 = "FillInTheCertificateActivity_EXTRA_IS_L3";
    private static final String EXTRA_ORDER_NUM = "FillInTheCertificateActivity_EXTRA_ORDER_NUM";

    private TitleView mTitleView;
    private LinearLayout mContainer;

    private int pageNum = 1;
    private String mVoucherNo;
    private PayDetail mPayDetail;

    private IconHintDialog mIconHintDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.print_activity_transaction);
        initView();
        initData();
    }

    private void initData() {
        // 根据订单号查询订单详情
        if (mVoucherNo != null && mVoucherNo.length() > 0) {
            mPayDetail = mPayDetailModel.getSuccessPayDetailByVoucherNo(mVoucherNo);
        }
        // 获取最后一条订单详情
        if (mPayDetail == null) {
            mPayDetail = mPayDetailModel.getLastSuccessTrade();
        }

        View view = new PrintController(this).getPreviewView(mPayDetail);
        mContainer.addView(view);
    }

    private void initView() {
        mVoucherNo = getIntent().getStringExtra(EXTRA_ORDER_NUM);

        mTitleView = findViewById(R.id.title_view);
        mTitleView.setRightImageVisibility(View.VISIBLE);
        mTitleView.setRightImageResource(R.drawable.printer);
        mTitleView.setCenterText(R.string.print_last_transaction);
        mTitleView.setLeftImageOnClickListener(
                v -> onBackPressed()
        );
        mTitleView.setRightImageOnClickListener(
                v -> startPrint()
        );

        mContainer = findViewById(R.id.view_container);
    }

    @Override
    public void onBackPressed() {
        L3BroadcastHelper.sendResultBroadcast(mContext, true, mPayDetail);
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissIconHintDialog();
    }

    private void startPrint() {
        try {
            int printStatus = DataPrinterKernel.INSTANCE().updatePrinterState();
            if (printStatus == 1 && mPayDetail != null) {
                print(pageNum);
            } else {
                showToast(R.string.error_printer);
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast(R.string.error_printer);
        }
        if (Params.sL3Params != null) {
            L3BroadcastHelper.sendResultBroadcast(mContext, true, mPayDetail);
            sendCloseAppBroadcast();
            finish();
        }
    }

    private void print(int pageNum) throws Exception {
        new PrintController().print(mPayDetail, mICallback, pageNum, true);
    }

    private ICallback mICallback = new BasePrintCallback() {

        @Override
        public void onPrintResult(int code, String msg) throws RemoteException {
            runOnUI(
                    () -> {
                        int maxPrintNumber = 2;
                        try {
                            SalesSlipPrintSettings settings = SalesSlipPrintSettingsOperation.getInstance().getSalesSlipPrintSettings();
                            String num = settings.getPrintReceiptSingleNum(); // 打印凭条单联数
                            maxPrintNumber = Integer.parseInt(num);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (code == 0) {
                            mPayDetail.isPrinted = true;
                            mPayDetailModel.updateIsPrintedByVoucherNo(mPayDetail.voucherNo, true);
                            if (pageNum < maxPrintNumber) {
                                pageNum++;
                                showPrintDialog();
                            } else {
                                mTitleView.setRightImageVisibility(View.GONE);
                            }
                        }
                    }
            );

        }

    };

    private void showPrintDialog() {
        if (mIconHintDialog == null) {
            mIconHintDialog = new IconHintDialog(this);
            mIconHintDialog.setRightText(R.string.ok);
            mIconHintDialog.setLeftText(R.string.cancel);
            mIconHintDialog.setMessage(R.string.index_print_next_joint);
            mIconHintDialog.setIconResource(R.drawable.state_warning);
            mIconHintDialog.setLeftOnClickListener(
                    v -> dismissIconHintDialog()
            );
            mIconHintDialog.setRightOnClickListener(
                    v -> {
                        dismissIconHintDialog();
                        startPrint();
                    }
            );
            mIconHintDialog.setCancelable(true);
            mIconHintDialog.setCanceledOnTouchOutside(true);
        }
        try {
            mIconHintDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissIconHintDialog() {
        if (mIconHintDialog != null) {
            try {
                mIconHintDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void startAction(Context context, String voucherNo) {
        startAction(context, voucherNo, false);
    }

    public static void startAction(Context context, String voucherNo, boolean isL3) {
        Intent intent = new Intent(context, FillInTheCertificateActivity.class);
        intent.putExtra(EXTRA_ORDER_NUM, voucherNo);
        intent.putExtra(EXTRA_IS_L3, isL3);
        context.startActivity(intent);
    }


}
